package cc.telecomdigital.tdstock.trading;

import java.util.ArrayList;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.activity.RealtimeStockActivity;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeLogout;
import cc.telecomdigital.tdstock.trading.Services.TradeLogout.ITradeLogoutResponse;
import cc.telecomdigital.tdstock.trading.widget.AppDialogImgOKCancel;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public final class Trade_tradingOptionActivity extends Trade_TemplateActivity
	implements AdapterView.OnItemClickListener, OnClickListener
{
	enum MENU_ACTION
	{
		STOCK_TRADE, ORDER_BOOK, STOCK_HOLDING, ACCT_BALANCE, CHANGE_PASSWORD
	}

	private class OptionItem
	{
		public int	textResId;
		public int	imgResId;
		public Object	tagObject;

		// iTag can be used for checking the return identification option
		public OptionItem(int iImageId, int iTextId, Object iTag)
		{
			imgResId = iImageId;
			textResId = iTextId;
			tagObject = iTag;
		}
	}

	private class OptionItemAdapter extends ArrayAdapter<OptionItem>
	{
		// Reference to the Item List
		private int	itemLayout;

		public OptionItemAdapter(Context iContext, int iListLayout,
				int iItemLayout, ArrayList<OptionItem> iItemList)
		{
			super(iContext, iListLayout, iItemList);
			itemLayout = iItemLayout;
		}

		@Override
		public View getView(int iPosition, View iContextView,
				ViewGroup iParent)
		{
			View viewObj = iContextView;
			if (viewObj == null)
			{
				LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				viewObj = inflatObj.inflate(itemLayout, null);
			}

			OptionItem item;

			item = this.getItem(iPosition);
			if (item != null)
			{
				ImageView imageViewObj = (ImageView) viewObj
						.findViewById(R.id.view_optionitemlist_Image);
				if (imageViewObj != null)
					imageViewObj.setImageResource(item.imgResId);

				TextView textViewObj = (TextView) viewObj
						.findViewById(R.id.view_optionitemlist_Text);
				if (textViewObj != null)
					textViewObj.setText(item.textResId);

			}
			return viewObj;
		}
	}

	private ArrayList<OptionItem>	optionItemList;
	private ListView			optionListView;
	// Create the array adapter to bind the array to the list view
	private OptionItemAdapter	optionItemAdapter;

	@Override
	public void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		setContentView(R.layout.tradingoption);

		// Create the array list of to do items
		optionItemList = new ArrayList<OptionItem>();

		optionItemList.add(new OptionItem(R.drawable.ic_listview_trade,
				R.string.stockTradeText, MENU_ACTION.STOCK_TRADE));
		optionItemList.add(new OptionItem(R.drawable.ic_listview_orderbook,
				R.string.transHistoryText, MENU_ACTION.ORDER_BOOK));
		optionItemList.add(new OptionItem(R.drawable.ic_listview_holding,
				R.string.holdingBalText, MENU_ACTION.STOCK_HOLDING));
		optionItemList.add(new OptionItem(R.drawable.ic_listview_acctbal,
				R.string.acctBalText, MENU_ACTION.ACCT_BALANCE));
		optionItemList.add(new OptionItem(R.drawable.ic_listview_chgpasswd,
				R.string.chgPasswordText, MENU_ACTION.CHANGE_PASSWORD));

		optionListView = (ListView) findViewById(R.id.tradeoption_List);
		optionListView.setOnItemClickListener(this);

		optionItemAdapter = new OptionItemAdapter(this,
				android.R.layout.simple_list_item_1,
				R.layout.view_optionitemlist, optionItemList);
		optionListView.setAdapter(optionItemAdapter);

		TextView textViewObj;
		// Set Header as UserName
		if (TradeAppInfo.IsDemoAccount())
		{			
			textViewObj = (TextView) findViewById(R.id.tradeoption_Title);
			textViewObj.setText(TradeAppInfo.GetUserName());
		}			

		findViewById(R.id.tradeoption_InfoBut).setOnClickListener(this);
		findViewById(R.id.tradeoption_LogoutBut).setOnClickListener(this);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		// Enforce scroll to the first, some the list does not drp
		if (optionListView != null)
		{
			optionListView.setSelectionFromTop(0, 0);
			optionListView.invalidate();
		}
	}

	@Override
	public void onBackPressed()
	{
		Class<? extends Activity>  sourceFrom;
		
		sourceFrom = TradeAppInfo.GetPrimaryEntryClass();
		if (sourceFrom == null)
			SwitchFreeActivity(RealtimeStockActivity.class);
		else
			SwitchFreeActivity(sourceFrom);
	}
	
	@Override
	public void onClick(View iViewObj)
	{
		int objId;

		objId = iViewObj.getId();

		switch (objId)
		{
			case R.id.tradeoption_InfoBut:
				//ShowPromptMessage(getString(R.string.disclaimerContentText));
				onBackPressed();				
				break;

			case R.id.tradeoption_LogoutBut:
				if (isTradeLogoutStart == true)
					break;
				RequestToLogout();			
				break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> iAdapter, View iViewObj,
			int iIndex, long iArgs)
	{
		int objId;

		objId = iAdapter.getId();
		switch (objId)
		{
			case R.id.tradeoption_List:
				// Because of the header, the IIndex need to be minus by one
				ProcessOptionListSelected((MENU_ACTION) (optionItemList
						.get(iIndex).tagObject));
				break;
		}
	}

	private void ProcessOptionListSelected(MENU_ACTION iAction)
	{
		Intent intentObj;

		switch (iAction)
		{
			case STOCK_TRADE:
				SwitchForwardActivity(Trade_StockInputActivity.class);
				break;
			case ORDER_BOOK:
				intentObj = new Intent(this, Trade_AcctComboActivity.class);
				// Put something on the bundle to mark the current state
				intentObj.putExtra(Trade_AppConstant.tradingStateBundle, 0);
				SwitchForwardActivity(Trade_AcctComboActivity.class, intentObj);
				break;
			case STOCK_HOLDING:
				intentObj = new Intent(this, Trade_AcctComboActivity.class);
				// Put something on the bundle to mark the current state
				intentObj.putExtra(Trade_AppConstant.tradingStateBundle, 1);
				SwitchForwardActivity(Trade_AcctComboActivity.class, intentObj);
				break;
			case ACCT_BALANCE:
				intentObj = new Intent(this, Trade_AcctComboActivity.class);
				// Put something on the bundle to mark the current state
				intentObj.putExtra(Trade_AppConstant.tradingStateBundle, 2);
				SwitchForwardActivity(Trade_AcctComboActivity.class, intentObj);
				break;
			case CHANGE_PASSWORD:
				SwitchForwardActivity(Trade_ChgPasswordActivity.class);
				break;
		}
	}

//	private static final int	CHECK_UPGRADE		= 1;
//	private static final int	SHOW_DISCLAIMER	= 2;
	private static final int	LOGOUT_ACCOUNT		= 1;

	// Create Menu when pressing the hard menu button below
	@Override
	public boolean onCreateOptionsMenu(Menu iMenu)
	{
		super.onCreateOptionsMenu(iMenu);
		// Add the menu Item to the menu
//		MenuItem menuItemObj = iMenu.add(0, SHOW_DISCLAIMER, Menu.NONE,
//				R.string.disclaimerText);
//		menuItemObj.setIcon(R.drawable.ic_menu_lightbulb);
//		menuItemObj.setShortcut('0', 'd');
//
//		menuItemObj = iMenu.add(0, CHECK_UPGRADE, Menu.NONE,
//				R.string.softUpdateText);
//		menuItemObj.setIcon(R.drawable.ic_menu_help);
//		menuItemObj.setShortcut('1', 'u');

		MenuItem menuItemObj = iMenu.add(0, LOGOUT_ACCOUNT, Menu.NONE,
				R.string.logoutText);
		menuItemObj.setIcon(R.drawable.ic_menu_logout);
		menuItemObj.setShortcut('0', 'e');

		return true;
	}

	// Selection from Menu menu
	@Override
	public boolean onOptionsItemSelected(MenuItem iMenu)
	{
		super.onOptionsItemSelected(iMenu);
		switch (iMenu.getItemId())
		{
//			case SHOW_DISCLAIMER:
//				ShowPromptMessage(getString(R.string.disclaimerContentText));
//				return true;
//
//			case CHECK_UPGRADE:
//				return true;

			case LOGOUT_ACCOUNT:
				if (isTradeLogoutStart == true)
					break;
				RequestToLogout();
				return true;
		}
		return false;
	}

//	@Override
//	public void onBackPressed()
//	{
//		RequestToLogout();
//	}

	private boolean isTradeLogoutStart = false;
	private void RequestToLogout()
	{
		AppDialogImgOKCancel logoutDialog;

		logoutDialog = new AppDialogImgOKCancel(this,
				R.drawable.ic_icon_logout);
		logoutDialog.SetTextContent(R.string.confirmToExitText);
		logoutDialog.show(new AppDialogImgOKCancel.IAppDialogImgOKCancel()
		{
			@Override
			public void OnOK_Click(DialogInterface iDialog)
			{
				if (TradeAppInfo.TradeApp_UseLogout)
				{
					TradeLogout request;
				
					isTradeLogoutStart = true;					
					ShowWaitingDialog();					
					request = new TradeLogout(actContext, TradeAppInfo.GetUserName());					
					request.SendRequest(TradeAppInfo.IsDemoAccount(), new ITradeLogoutResponse()
					{
						@Override
						public void ResponseFunc(boolean iSuccessfulSend)
						{
							isTradeLogoutStart = false;
							DismissWaitingDialog_Background();
							AccountLogout();							
						}						
					});
					return;
				}
				
				AccountLogout();
			}

			@Override
			public void OnDialogCancel(DialogInterface iDialog)
			{
			}

			@Override
			public void OnCancel_Click(DialogInterface iDialog)
			{
			}
		}, true);
	}

	private void AccountLogout()
	{	
		if (TradeAppInfo.TradeApp_UseLogout)
		{
			TradeAppInfo.ResetAllInfo();
					
			//If it is not delay mode, we should allow user to use again
			if (!TradeAppInfo.IsAllowDemoOnly(appHost.GetLSClient_ServicePlan()))
				TradeAppInfo.SetAsDemoAccount(false);			
			
//			RealtimeStockActivity.SetTabIndex(RealtimeStockActivity.TAB_INDEX_STOCK);
//			SwitchFreeActivity(RealtimeStockActivity.class);
			Class<? extends Activity>  sourceFrom;
			
			sourceFrom = TradeAppInfo.GetPrimaryEntryClass();
			if (sourceFrom == null)
				SwitchFreeActivity(RealtimeStockActivity.class);
			else
				SwitchFreeActivity(sourceFrom);			
			return;						
		}
		
		SetToLoginActivity();
	}
	
	
//	private AppDialogOK promptMessage = null;
//	private void ShowPromptMessage(String iContent)
//	{
//		if (promptMessage != null)
//			promptMessage.dismiss();
//		
//		promptMessage = ShowInfoBox(iContent);
//	}		
}
